<template>
    <el-dialog
        v-dialogDrag
        :title="dialogType == 1 ? '新增' : '修改'"
        :close-on-click-modal="false"
        :visible.sync="visible"
        width="70%"
        @close="handleClose"
        :center="true"
    >
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="170px">
            <el-form-item label="标题">
                <el-input v-model="dataForm.title" placeholder="请输入标题" clearable></el-input>
            </el-form-item>

            <el-form-item label="类型" prop="typeName">
                <el-select v-model="typeName" placeholder="请选择" style="width: 100%" :disabled="typeNameSelectedDis">
                    <el-option v-for="(item, index) in typeNamePtions" :key="index" :label="item.Name" :value="item.Id"> </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="图片:">
                <div style="color: red">(尺寸要求:300*127)</div>

                <moreUpload
                    :initfileList="iconUrlListUrl"
                    :isMultiple="false"
                    :upFileNum="1"
                    @moreUploadHandleExceed="moreUpFileHandleExceed"
                    @moreUpFileHandleRemove="iconMoreUpFileHandleRemove"
                    @update="updateIconUrl"
                ></moreUpload>
            </el-form-item>

            <el-form-item label="排序号" prop="sort">
                <el-input-number v-model="dataForm.sort" controls-position="right" :min="1" label="排序号"> </el-input-number>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import API from '@/api';
import cloneDeep from 'lodash/cloneDeep';
import upload from '../../components/upLoad/index';
import moreUpload from '../../components/upLoad/moreUpload';
export default {
    components: {
        upload,
        moreUpload
    },
    data() {
        return {
            visible: false,
            dataForm: {
                title: '', //标题
                pictureUrl: '', //图片
                type: '', // 类型
                sort: '' //排序号
            },
            appId: '',
            dataRule: {
                title: [
                    {
                        required: true,
                        message: '名称不能为空',
                        trigger: 'blur'
                    }
                ],
                pictureUrl: [
                    {
                        required: true,
                        message: '请上传图片',
                        trigger: 'blur'
                    }
                ]
            },

            //类型
            typeName: '农产品专区',
            typeNameSelectedDis: false,
            typeNamePtions: [
                { Id: '/farmProducts?type=NCP', Name: '农产品专区', selected: true },
                { Id: '/farmProducts?type=NZ', Name: '农资专区', selected: false },
                { Id: '/property', Name: '产权专区', selected: false },
                { Id: '/shareCropland', Name: '共享农田专区', selected: false }
            ],

            //图片
            iconUrlList: [],
            iconUrlListUrl: [],

            dialogType: 1
        };
    },
    methods: {
        handleClose() {
            this.dataForm = {
                title: '', //标题
                pictureUrl: '', //图片
                type: '', // 类型
                sort: '' //排序号
            };
            //图片数据清空
            this.iconUrlList = [];
            this.iconUrlListUrl = [];
            this.$refs['dataForm'].resetFields();
        },
        update(img) {
            this.dataForm.imgUrl = img;
        },
        init(item, type) {
            this.visible = true;
            this.dialogType = type;
            if (item && type == 2) {
                this.getPageData(item.id);
            }
        },

        //获取页面详情
        getPageData(id) {
            var _that = this;
            let params = {
                id: id
            };
            API.homeImg.queryHomeImgDetail(params).then((res) => {
                _that.dataForm = res.result;
                //处理类型选择
                if (_that.type != null && _that.type !== '') {
                    _that.typeName = this.getTypeNameptions(null, _that.dataForm.type);
                }

                //处理图片
                var imgUrlQz = window.baseUrl + '/sys/file/showpic?id=';

                //======= 字符串，拆分id数组，拆分Url数组，拆分标识，url前缀
                this.disposePublicStrSplit(_that.dataForm.pictureUrl, _that.iconUrlList, _that.iconUrlListUrl, 'url', imgUrlQz);
            });
        },

        disposePublicStrSplit(fileStr, splicList, splicUrlList, splicFlag, urlConnection) {
            //字符串，拆分id数组，拆分Url数组，拆分标识，url前缀

            if (fileStr != null && fileStr !== '') {
                //== 1.拆分字符串 ’a:b,b:a‘ 为数组
                splicList = fileStr.split(',');

                for (let index = 0; index < splicList.length; index++) {
                    //== 2.数组中的 ’a:b‘ 在拆分 为数组
                    const element = splicList[index];
                    var elmentList = element.split(':');

                    //== 3.向 上传 绑定的数据集，添加[name，url，id] 数据
                    if (elmentList.length > 0) {
                        if (splicFlag === 'url') {
                            //文件名，文件地址（url)，文件id
                            splicUrlList.push({ name: elmentList[1], url: urlConnection + elmentList[0], urlId: elmentList[0] });
                        } else {
                            //文件名，文件地址(可id或url)，文件id
                            splicUrlList.push({ name: elmentList[1], url: elmentList[0], urlId: elmentList[0] });
                        }
                    } else {
                        //== 3.x  做预防,有可能字符串为’a,b‘ 没有分号

                        if (splicFlag === 'url') {
                            splicUrlList.push({ name: '文件' + index, url: urlConnection + element, urlId: element });
                        } else {
                            //文件名，文件地址(可id或url)，文件id
                            splicUrlList.push({ name: '文件' + index, url: element, urlId: element });
                        }
                    }
                }
            }
        },

        getTypeNameptions(params, name) {
            if (this.isChinese(name)) {
                //全是中文，代表用户没有选择，为默认值，或者
                for (var i = 0; i < this.typeNamePtions.length; i++) {
                    if (this.typeNamePtions[i].Name === name) {
                        this.dataForm.type = this.typeNamePtions[i].Id;
                        params.type = this.typeNamePtions[i].Id;

                        return this.typeNamePtions[i].Id;
                    }
                }
            } else {
                //选择之后，name为代码id
                for (var i = 0; i < this.typeNamePtions.length; i++) {
                    if (this.typeNamePtions[i].Id === name) {
                        this.dataForm.type = this.typeNamePtions[i].Id;
                        params.type = this.typeNamePtions[i].Id;
                        return this.typeNamePtions[i].Id;
                    }
                }
            }
        },

        //是否全是 中文
        isChinese(temp) {
            var re = /[^\u4e00-\u9fa5]/;
            if (re.test(temp)) return false;
            return true;
        },

        /**
         * 图片 上传
         */

        // 图片 上传文件  成功回调
        updateIconUrl([url, sigleImgId, response, file, fileList]) {
            this.diosposeImageOp([file, fileList]);
        },
        // 删除文件回调
        iconMoreUpFileHandleRemove([file, fileList]) {
            this.diosposeImageOp([file, fileList]);
        },
        diosposeImageOp([file, fileList]) {
            this.iconUrlList = [];

            for (let index = 0; index < fileList.length; index++) {
                const element = fileList[index];
                console.log('上传的图片：', element);

                if (element.response != null) {
                    //不等于空为刚上传的文件
                    this.iconUrlList.push(element.response.result[0] + ':' + element.name);
                } else {
                    //为空为之前上传的文件
                    this.iconUrlList.push(element.urlId + ':' + element.name);
                }
            }
        },
        moreUpFileHandleExceed([files, fileList]) {
            this.$message.warning(`超过了图片上传限制，当前只允许上传一张图片`);
        },

        // 表单提交
        dataFormSubmit() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    let params = cloneDeep(this.dataForm);

                    //处理选择
                    this.getTypeNameptions(params, this.typeName);

                    //处理图片
                    if (this.iconUrlList.length == 0) {
                        this.$message.error(`图片为必传，请上传图片`);
                        return ;
                    }

                    if (this.iconUrlList.length > 0) {
                        this.dataForm.pictureUrl = this.iconUrlList.join(',');
                        params.pictureUrl = this.dataForm.pictureUrl;
                    }

                    var tick = this.dialogType == 1 ? API.homeImg.addHomeImg(params) : API.homeImg.editHomeImg(params);

                    tick.then((data) => {
                        if (data.code == '0000') {
                            this.$message({
                                message: `${this.dialogType == 2 ? '修改成功' : '新增成功'}`,
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.visible = false;
                                    this.$emit('refreshDataList');
                                }
                            });
                        }
                    });
                }
            });
        }
    }
};
</script>